from rest_framework import serializers
from .models import Complaint
from accounts.models import User, Technician
from orders.models import Order

class ComplaintSerializer(serializers.ModelSerializer):
    customer_name = serializers.CharField(source='customer.username', read_only=True)
    technician_name = serializers.CharField(source='technician.real_name', read_only=True)
    order_id = serializers.IntegerField(source='order.id', read_only=True)
    
    class Meta:
        model = Complaint
        fields = '__all__'
        read_only_fields = ['id', 'customer', 'created_at', 'updated_at', 'resolved_at']

class CreateComplaintSerializer(serializers.ModelSerializer):
    class Meta:
        model = Complaint
        fields = ['technician', 'order', 'complaint_type', 'title', 'content', 'evidence_images']
    
    def validate(self, data):
        # 验证技师是否存在且已认证
        technician = data['technician']
        if not technician.is_verified:
            raise serializers.ValidationError("技师未认证")
        
        # 如果提供了订单，验证订单是否存在且属于当前用户
        if data.get('order'):
            order = data['order']
            if order.customer != self.context['request'].user:
                raise serializers.ValidationError("订单不属于当前用户")
            
            if order.technician != technician:
                raise serializers.ValidationError("订单与技师不匹配")
        
        return data

class UpdateComplaintSerializer(serializers.ModelSerializer):
    class Meta:
        model = Complaint
        fields = ['status', 'resolution']
        read_only_fields = ['id', 'customer', 'technician', 'order', 'complaint_type', 'title', 'content', 'evidence_images', 'created_at', 'updated_at']